<template>
  <div class="login">
    <div class="ms-login">
      <!-- 表单区域 -->
      <div class="ms-title">口罩机操作系统</div>
      <el-form :model="ruleForm2"
               status-icon
               :rules="rules2"
               ref="ruleForm2"
               label-width="80px"
               class="demo-ruleForm">
        <el-form-item label="工号"
                      prop="workerid">
          <el-input type="text"
                    v-model="ruleForm2.workerid"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="pass">
          <el-input type="password"
                    show-password
                    v-model="ruleForm2.pass"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="机位"
                      prop="machineid">
          <!-- <el-input v-model="ruleForm2.machineid"></el-input> -->
          <el-select v-model="ruleForm2.machineid"
                     clearable
                     filterable
                     placeholder="请选择">
            <el-option v-for="item in allMachine"
                       :key="item.ID"
                       :label="item.MachineName"
                       :value="item.ID">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     class="login_Btn"
                     @click="submitForm('ruleForm2')">登录</el-button>
          <el-button @click="resetForm('ruleForm2')"
                     class="clear_Btn">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'login',
  components: {},
  mounted() {
    // 清缓存
    this.$store.commit('updateMachineStatus', null)
    this.$store.commit('updateMachineSpeed', null)
    // 获取设备信息
    this.getMachineInfo()
  },
  data() {
    // 验证规则(注意：必须保证每个判断分支有callback回调)
    var workeridPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入工号'))
      } else {
        callback()
      }
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    var checkMachine = (rule, value, callback) => {
      if (!value) {
        callback(new Error('机位不能为空'))
      } else {
        callback()
      }
    }
    return {
      ruleForm2: {
        workerid: '', // 工号
        pass: '', // 密码
        machineid: '', // 机号
        usertype: 1 // 0是管理员，1是员工
      },
      rules2: {
        workerid: [{ validator: workeridPass, trigger: 'blur' }], // 工号规则
        pass: [{ validator: validatePass, trigger: 'blur' }], // 密码规则
        machineid: [{ validator: checkMachine, trigger: 'blur' }] // 机号规则
      },
      allMachine: [], // 所有设备
      selectedMacInfo: null //已选择的设备
    }
  },
  methods: {
    // 获取机器信息
    async getMachineInfo() {
      // 请求机器id数据
      let url = '/api/CommonExtenalAPI/MacineInfo'
      const res = await this.$axios({
        method: 'GET',
        url: url
      })
      // 判断设备是否获取成功
      if (res.Code == 204) {
        this.$message({
          type: 'error',
          message: '设备数据获取失败，请刷新重试!',
          duration: 1500
        })
      } else if (res.Code == 200) {
        this.allMachine = res.Data
      }
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        // 表单验证规则是否通过
        if (valid) {
          console.log('表单验证通过')
          // 存储设备
          this.storageDevice()
          // 请求数据
          this.requestData()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 登录
    requestData() {
      console.log('开始请求数据')
      // // 发送请求,用GET方式
      let url = '/api/Login/UserInfo'
      // 请求参数
      let data = {
        UserNo: this.ruleForm2.workerid,
        Password: this.ruleForm2.pass
      }
      this.$axios({
        method: 'GET',
        url: url,
        params: data
      })
        .then(res => {
          // 判断用户是否存在
          if (res.Code === 2003) {
            // 登录失败
            this.$message({
              type: 'error',
              message: res.Message,
              duration: 1500
            })
            return
          }
          // 0 登录成功
          this.$message({
            type: 'success',
            message: res.Message,
            duration: 1500
          })
          // 1 获取User+selectedmacine信息
          const UserInfo = res.Data
          const selectedMacInfo = this.selectedMacInfo
          // 2 组成完整对象
          const totalInfo = { UserInfo, selectedMacInfo }
          // 3 存入cookie
          this.$cookies.set('totalInfo', totalInfo, '7d', '/')
          // 4 token存入store
          this.$store.commit('updateToken', UserInfo.Token)
          // console.log('拿取一下coookie：', this.$cookies.get('totalInfo'))
          // 5 跳转
          this.$router.push('/home')
        })
        .catch(err => {
          this.$message({
            type: 'error',
            message: '登录失败!',
            duration: 1500
          })
          console.log('登陆失败')
        })
    },
    // 查找对应设备 并存到缓存
    storageDevice() {
      this.selectedMacInfo = this.allMachine.filter((item, index) => item.ID === this.ruleForm2.machineid)[0]
    }
  }
}
</script>

<style lang="less">
@import './login.less';
</style>

